package com.template.templateuser.domain.service;

import com.template.templateuser.domain.dto.SysDeptDTO;
import com.template.templateuser.domain.mapper.SysDeptMapper;
import com.template.templateuser.domain.util.PageInfo;
import com.template.templateuser.domain.web.param.FindSysDeptListParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SysDeptServiceImpl implements SysDeptService {


    @Autowired
    SysDeptMapper sysDeptMapper;

    @Override
    public PageInfo<SysDeptDTO> getSysDeptList(FindSysDeptListParam findSysDeptListParam) {
        PageInfo<SysDeptDTO> pageInfo=new PageInfo(findSysDeptListParam.getPageNum(),findSysDeptListParam.getPageSize());

        int sysDeptCount = sysDeptMapper.getSysDeptCount(findSysDeptListParam);
        if(sysDeptCount>0){
            pageInfo.setTotal(sysDeptCount);
            List<SysDeptDTO> sysDeptList = sysDeptMapper.getSysDeptList(findSysDeptListParam,pageInfo.getOffset(),pageInfo.getPageSize());
            pageInfo.setItems(sysDeptList);
        }
        return pageInfo;
    }

    @Override
    public int saveSysDept(SysDeptDTO sysDeptDTO) {
        return sysDeptMapper.save(sysDeptDTO);
    }

    @Override
    public int updateSysDept(Long id, SysDeptDTO sysDeptDTO) {
        sysDeptDTO.setId(id);
        return  sysDeptMapper.updateById(sysDeptDTO);
    }

    @Override
    public SysDeptDTO querySysDept(Long id) {
        return sysDeptMapper.findSysDeptById(id);
    }

    @Override
    public int deleteSysDept(Long id) {
        SysDeptDTO sysDeptDTO =new SysDeptDTO();
        sysDeptDTO.setId(id);
        sysDeptDTO.setDeleted(1);
        return sysDeptMapper.updateById(sysDeptDTO);
    }

    @Override
    public List<SysDeptDTO> getSysDeptListTree() {
        //SELECT * from sys_dept  where deleted=0
        List<SysDeptDTO> sysDeptAllList = sysDeptMapper.getSysDeptAllList();
        if(sysDeptAllList!=null&&sysDeptAllList.size()>0){
            Map<Long, List<SysDeptDTO>> collect = sysDeptAllList.stream()
                    .collect(Collectors.groupingBy(SysDeptDTO::getParentId));
            List<SysDeptDTO> allFirstParent = sysDeptAllList.stream().
                    filter(a -> a.getParentId().equals(0L)).collect(Collectors.toList());
            //

            for(SysDeptDTO dto:sysDeptAllList){
                dto.setChildren(collect.get(dto.getId()));
            }
            for(SysDeptDTO dto:allFirstParent){
                dto.setChildren(collect.get(dto.getId()));
            }
            return allFirstParent;
        }
        return null;
    }

    @Override
    public List<SysDeptDTO> getSysDeptListByParentId(Long parentId) {
        return sysDeptMapper.getSysDeptListByParentId(parentId);
    }
}
